<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WebSocket</title>
<style type="text/css">
	html,body{margin: 0; padding: 0;}
	::-webkit-scrollbar { height: 10px; width: 10px; background: rgba(230,230,230, .8);}
	::-webkit-scrollbar-thumb { border-radius: 5px; background: rgba(150,150,150, .6);}
	.main{position:absolute;width:100%;height:100%;z-index:-1;}
	.content{width:1046px;margin:10px auto 0;border:1px solid #CCC;border-radius:4px;}
	.text{width:756px;height:36px;line-height:34px;font-size:16px;padding-left:6px;border-radius:4px;
		border:1px solid #CCC; float:left; font-family: Verdana,serif;color: #555;}
	.textarea {height:80px;line-height:24px; }
	.button{width:120px;height:40px;line-height:38px;font-size:20px;border-radius:4px;color:#505050;
		border:1px solid #CCC; background-color: #EEE; cursor:pointer; float:left; margin-left:10px;}
	.button2 {height:85px; line-height: 80px; }
	.text:focus, .button:focus {outline:none; -moz-outline:none; border-color:#A6A6A6;}
	#connect-div{padding:8px; height:40px;}
	#message-div{height:615px;border-top:1px solid #CCC;border-bottom:1px solid #CCC;padding:8px;overflow-y:auto;}
	#message-div >div{margin-bottom:10px;}
	#send-div{padding:8px; height:86px;}
	.clear-button{width:120px;}
	.client{color:green;}
	.server{color:#00f;}
	.connect{color:red;}
	.message{color:#555;}
	#hideId{position:absolute;width:100px;}
	#connectId{color:green;}
	#closeId{color:red;}
	#showId{color:#00f;background-color:#fff;}
	#sendId{color:#fff;background-color:#0d95f0;}
</style>
</head>
<body>

<div class="main">
	<div id="context-div" class="content">
		<div id="connect-div">
			<input id="urlId" class="text" type="text" value="ws://127.0.0.1:9000" required="true" placeholder="请输入websocket地址，如：ws://127.0.0.1:9000">
			<button id="connectId" class="button" type="button" onclick="connectWebSocket()">连接</button>
			<button id="closeId" class="button" type="button" onclick="closeWebSocket()">断开</button>
		</div>

		<div id="message-div" ></div>

		<div id="send-div">
			<textarea id="messageId" class="text textarea" required="true" placeholder="发送消息">ping</textarea>
			<button id="sendId" class="button button2" type="button" onclick="sendMessage()">发送消息</button>
			<button id="clearId" class="button button2" type="button" onclick="clearMessage()">清空消息</button>
		</div>
	</div>
</div>

<script>

	var ws = null;

	//window.onload = connectWebSocket;

	function isConnect() {
		return ws && ws.readyState === WebSocket.OPEN;
	}

	function connectWebSocket() {
		if(isConnect()) {
			creatdiv("WebSocket 已连接", "");
			return;
		}
		if(!window.WebSocket) {
			creatdiv("您的浏览器不支持 WebSocket 协议！", "");
			return;
		}
		var wsPath = document.getElementById('urlId').value.trim();
		if(!wsPath || wsPath === 'ws://' || wsPath === 'wss://') {
			console.log("请输入正确的 WebSocket 地址");
			return;
		}
		try {
			ws = new WebSocket(wsPath);

			ws.onopen = function(event) {
				console.log("WebSocket 连接成功：" + wsPath);
				creatdiv("WebSocket 连接成功", "");
			};

			ws.onmessage = function(event) {

				console.log("我收到消息：" + event.data);
				creatdiv(event.data, "服务端 ");

				if (event.data === 'pong') {
					return;
				}
				else if (event.data === 'ping') {
					sendMessage('pong');
					return;
				}

				try {
					var objData = JSON.parse(event.data);
					if (!objData || !objData.action) {
						return;
					}
					switch (objData.action) {
						case 'pong':
							return;

						case 'ping':
							sendMessage('{"action": "pong", "count": "' + objData.count || 0 + '"}');
							return;

						default:
							return;
					}
				}
				catch (err) {
					console.log('JSON.parse: ', err.toString());
				}
			};

			ws.onclose = function(event) {
				console.log("WebSocket 断开：" + wsPath);
				creatdiv("WebSocket 断开", "");
			};

			ws.onerror = function(event) {
				console.log("WebSocket 异常：" + wsPath);
				creatdiv("WebSocket 异常", "");
			};
		}
		catch (err) {
			creatdiv(err.toString(), "");
		}
	}

	function closeWebSocket() {
		if(isConnect()) {
			ws.close();
		} else {
			console.log("WebSocket 已断开. ");
			creatdiv("WebSocket 已断开", "");
		}
	}

	function sendMessage(message = '') {
		if (!isConnect()) {
			connectWebSocket();
		}
		setTimeout(function () {
			message = message ? message : document.getElementById('messageId').value.trim();
			console.log("发送数据: ", message);
			creatdiv(message, "我 ");
			ws.send(message);
		}, 200);
	}

	//清空消息
	function clearMessage() {
		var messageDiv = document.getElementById('message-div');
		var pObjs = messageDiv.childNodes;
		for (var i = pObjs.length - 1; i >= 0; i--) {
		  messageDiv.removeChild(pObjs[i]);
		}
	}

	//监听窗口关闭事件，当窗口关闭时，主动去关闭 WebSocket 连接，防止连接还没断开就关闭窗口，server端会抛异常。
	window.onbeforeunload = function() {
		closeWebSocket();
	}

	//按键处理
	document.getElementById('urlId').onkeypress = function(e) {
		e = e ? e : window.event;
		var code = e.keyCode || e.which || e.charCode;
		if (code === 13) { //回车
			connectWebSocket();
		}
	}
	document.getElementById('messageId').onkeypress = function(e) {
		e = e ? e : window.event;
		if (e.ctrlKey && e.code === 'Enter') {
			sendMessage();
		}
	}

	//创建一个div
	function creatdiv(message, user) {
		var now = time();
		var sendDiv = document.createElement('div');
		var userDiv = document.createElement('div');
		var messageDiv = document.getElementById('message-div');
		userDiv.innerHTML = user + now;
		if(user === "我 ") {
			userDiv.className = "client";
			sendDiv.className = "message";
		} else if(user === "服务端 ") {
			userDiv.className = "server";
			sendDiv.className = "message";
		} else {
			userDiv.className = "message";
			sendDiv.className = "connect";
		}
		sendDiv.innerText = message; //注意过滤js
		userDiv.appendChild(sendDiv);
		messageDiv.appendChild(userDiv);
		messageDiv.scrollTop = messageDiv.scrollHeight + 80;
	}

	function time()
	{
		var date = new Date();
		var YY = date.getFullYear();
		var mm = date.getMonth()+1;
		var dd = date.getDate();
		var hh = date.getHours();
		var ii = date.getMinutes();
		var ss = date.getSeconds();
		mm = mm < 10 ? "0" + mm : mm;
		dd = dd < 10 ? "0" + dd : dd;
		hh = hh < 10 ? "0" + hh : hh;
		ii = ii < 10 ? "0" + ii : ii;
		ss = ss < 10 ? "0" + ss : ss;
		return hh +":"+ ii +":"+ ss;
	}
</script>
</body>
</html>
